﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

/*
 * To - Do Feature List
 * 
 * A button that pulls the status of current sockets
 *
 */

namespace Talk.Net.Server
{
	/// <summary>
	/// Interaction logic for Main.xaml
	/// </summary>
	public partial class Main : Window
	{
		SocketServer server = null;

		// I hate the UI thread
		private delegate void AppendLogDelegate(string message);
		AppendLogDelegate appendLogDelegate;

		private delegate void ProcessContentDelegate(byte[] audio);
		ProcessContentDelegate processContentDelegate;
		
		public Main()
		{
			InitializeComponent();
			appendLogDelegate = new AppendLogDelegate(AppendLog);
			processContentDelegate = new ProcessContentDelegate(ProcessContent);

			// the AV needs to be revamped to handle 2 channel audio
			// AV.Render();		
		}

		private void ProcessContent(byte[] content)
		{
			// the AV needs to be revamped to handle 2 channel audio
			int ChannelLength = content.Length / 2;
			byte[] LeftChannel = new byte[ChannelLength];
			byte[] RightChannel = new byte[ChannelLength];

			for (int i = 0; i < ChannelLength; i++)
			{
				LeftChannel[i] = content[(i*2)];
				RightChannel[i] = content[(i*2) + 1];
			}
			 avLeftChannel.SetAudio(LeftChannel);
			 avRightChannel.SetAudio(RightChannel);
		}

		private void AppendLog(string message)
		{
			textBox1.AppendText(DateTime.Now.ToString() + " : " + message + Environment.NewLine);
			textBox1.ScrollToEnd();
		}

		private void button1_Click(object sender, RoutedEventArgs e)
		{
			ContentManager.ContentNotification += new ContentManager.ContentNotifierDelegate(ContentManager_ContentNotification);
			server = new SocketServer();
			server.LogEvent += new SocketServer.LogEventDelegate(server_LogEvent);
			server.Startup();

			button1.IsEnabled = false;
			button2.IsEnabled = true;
		}

		void ContentManager_ContentNotification(byte[] content)
		{
			Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, processContentDelegate, content);
		}

		void server_LogEvent(string message)
		{
			Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, appendLogDelegate, message);
		}

		private void button2_Click(object sender, RoutedEventArgs e)
		{
			if (server != null)
				server.Shutdown();

			button1.IsEnabled = true;
			button2.IsEnabled = false;
		}
	}
}
